import React, { useState, useEffect } from 'react';
import { Text, TouchableOpacity, ScrollView, StyleSheet } from 'react-native';
import {
  Button,
  Flex,
  InputItem,
  List,
  Picker,
  TextareaItem,
  Toast,
} from '@ant-design/react-native';
import PhotoCameraPicker from '@/rcomponents/photoCameraPicker';
import { ATA_DATA } from '@/constants';
import DamageReportStore from './damageRptStore';
import UserStore from '@/stores/userStore';

const styles = StyleSheet.create({
  cancelBtn: {
    backgroundColor: '#ebedf0',
    paddingHorizontal: 10,
    borderRadius: 5,
    paddingVertical: 5,
    borderWidth: 0,
    margin: 5,
  },
});
// 结构损伤上报页面
function DamageReportSubmitPage({ navigation, route }) {
  const damageRpt = route.params;
  const [tid, setTid] = useState({
    sectionTid: '',
    partTid: '',
    damageTypeTid: '',
  });
  const [ataParams, setAtaParams] = useState({
    section: [],
    part: [],
    damageType: [],
  });

  useEffect(() => {
    // loadReport(id) setAta
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity onPress={handleBack} style={styles.cancelBtn}>
          <Text>取消</Text>
        </TouchableOpacity>
      ),
    });
  }, []);

  const [editDamage, setEditDamage] = useState({
    chapter: '',
    section: '',
    part: '',
    damageType: '',
  });
  const damageRptStore = DamageReportStore.useStore();
  const userStore = UserStore.useStore();
  const handleBack = () => {
    navigation.goBack();
  };

  useEffect(() => {
    setAtaParams(ataParams);
    setTid(tid);
  }, [setAtaParams, ataParams, tid, setTid]);

  const handleAtaChange = async (field, value, type, Tid) => {
    if (type === '') {
      const sectionRes = await damageRptStore.getDamageReport({
        Ata: value[0],
        RegNo: damageRpt.acno,
        StType: 'section',
      });

      sectionRes.errorMsg ? Toast.fail(sectionRes.errorMsg) : '';
      const sectionData =
        sectionRes.data !== null
          ? sectionRes.data.map((item, index) => ({
              label: item.Name,
              value: index,
              SectionTid: item.Tid,
            }))
          : [];
      const partRes = await damageRptStore.getDamageReport({
        Ata: value[0],
        RegNo: damageRpt.acno,
        StType: 'part',
      });

      partRes.errorMsg ? Toast.fail(partRes.errorMsg) : '';
      const partData =
        partRes.data !== null
          ? partRes.data.map((item, index) => ({
              label: item.Name,
              value: index,
              PartTid: item.Tid,
            }))
          : [];
      setAtaParams({
        ...ataParams,
        part: partData,
        section: sectionData,
      });
    } else if (type === 'damageType') {
      const damageTypeRes = await damageRptStore.getDamageReport({
        Ata: editDamage.chapter[0],
        RegNo: damageRpt.acno,
        StType: 'damageType',
        SectionTid: field === 'section' ? Tid : tid.sectionTid,
        PartTid: field === 'part' ? Tid : tid.partTid,
      });
      damageTypeRes.errorMsg ? Toast.fail(damageTypeRes.errorMsg) : '';
      const damageData =
        damageTypeRes.data !== null
          ? damageTypeRes.data.map((item, index) => ({
              label: item.Name,
              value: index,
              DamageTid: item.Tid,
            }))
          : [];
      setAtaParams({
        ...ataParams,
        damageType: damageData,
      });
    } else {
      if (
        editDamage.chapter[0] &&
        damageRpt.acno &&
        tid.sectionTid &&
        tid.partTid &&
        Tid
      ) {
        const res = await damageRptStore.getDamageReport({
          Ata: editDamage.chapter[0],
          RegNo: damageRpt.acno,
          StType: 'para',
          SectionTid: tid.sectionTid,
          PartTid: tid.partTid,
          DamageTypeTid: Tid,
        });
        res.errorMsg ? Toast.fail(res.errorMsg) : '';
        const arr =
          res.data !== null
            ? res.data.map((item) => {
                const Name = item.Name;
                return Name;
              })
            : [];

        setAtaParams({ ...ataParams, showArea: arr });
      }
    }
    setEditDamage({ ...editDamage, [field]: value });
  };

  const handleChange = (field, value) => {
    setEditDamage({ ...editDamage, [field]: value });
  };
  const handlePicChange = (field, value) => {
    setEditDamage({
      ...editDamage,
      [field]: [editDamage[field], value].filter((f) => f).join(','),
    });
  };
  const handleSubmit = async () => {
    editDamage.visionRangePics ? '' : Toast.fail('请维护近景图片信息');
    editDamage.closeShotPics ? '' : Toast.fail('请维护远景图片信息');
    editDamage.damageDesc ? '' : Toast.fail('请维护位置描述信息');
    tid.sectionTid ? '' : Toast.fail('请维护section信息');
    tid.partTid ? '' : Toast.fail('请维护part信息');
    tid.damageTypeTid ? '' : Toast.fail('请维护损伤类型信息');
    const paraName = ataParams.showArea;
    const paraValue = [];
    for (let i = 0; i < paraName.length; i++) {
      paraValue[i] = editDamage[`${paraName[i]}`];
      paraValue[i] === ''
        ? Toast.fail('请维护合法的（数字）' + paraName[i] + '信息')
        : '';
    }
    // sectionName
    const sectionIndex = (ataParams.section || []).findIndex(
      (section) => section.SectionTid == tid.sectionTid,
    );
    const sectionName = ataParams.section[sectionIndex].label;
    // partName
    const partIndex = (ataParams.part || []).findIndex(
      (part) => part.PartTid == tid.partTid,
    );
    const partName = ataParams.part[partIndex].label;
    // damageTypeName
    const damageTypeIndex = (ataParams.damageType || []).findIndex(
      (damageType) => damageType.DamageTid == tid.damageTypeTid,
    );

    const damageTypeName = ataParams.damageType[damageTypeIndex].label;

    const damageReport = {
      Ata: editDamage.chapter[0],
      RegNo: damageRpt.acno,
      SectionTid: String(tid.sectionTid),
      PartTid: String(tid.partTid),
      DamageTypeTid: String(tid.damageTypeTid),
      StType: 'submit',
      TaskNo: damageRpt.jobCard,
      Position: editDamage.damageDesc,
      SectionName: sectionName,
      PartName: partName,
      DamageTypeName: damageTypeName,
      Station: damageRpt.airport,
      PicPaths: editDamage.closeShotPics + ',' + editDamage.visionRangePics,
      ParaName: paraName.join(','),
      ParaValue: paraValue.join(','),
    };
    const res = await damageRptStore.submitDamageReport(
      userStore.user.LoginName,
      damageReport,
    );
    if (res.errorMsg) {
      Toast.success('提交失败，请重试！');
    } else {
      Toast.success('提交成功！');
    }
    navigation.goBack();
  };

  return (
    <>
      <ScrollView keyboardShouldPersistTaps={'always'} nestedScrollEnabled>
        <List>
          <InputItem value={damageRpt.acno} editable={false}>
            机号
          </InputItem>
          <InputItem value={damageRpt.jobCard} editable={false}>
            来源工作
          </InputItem>
          <InputItem value={damageRpt.airport} editable={false}>
            航站
          </InputItem>
          <Picker
            data={ATA_DATA.slice(51, 58)}
            cols={1}
            value={editDamage.chapter}
            onChange={(val) => {
              handleAtaChange('chapter', val, '');
            }}
          >
            <List.Item>章节</List.Item>
          </Picker>
          <Picker
            data={ataParams.section}
            cols={1}
            value={editDamage.section}
            onChange={(val) => {
              setEditDamage({ ...editDamage, section: val });
              const sectionTid = ataParams.section[val[0]].SectionTid;
              setTid({
                ...tid,
                sectionTid,
              });
              handleAtaChange('section', val, 'damageType', sectionTid);
            }}
          >
            <List.Item>SECTION</List.Item>
          </Picker>
          <Picker
            data={ataParams.part}
            cols={1}
            value={editDamage.part}
            onChange={(val) => {
              setEditDamage({ ...editDamage, part: val });
              const partTid = ataParams.part[val[0]].PartTid;
              setTid({
                ...tid,
                partTid,
              });
              handleAtaChange('part', val, 'damageType', partTid);
            }}
          >
            <List.Item>Part</List.Item>
          </Picker>
          <Picker
            data={ataParams.damageType}
            cols={1}
            value={editDamage.damageType}
            onChange={(val) => {
              const damageTypeTid = ataParams.damageType[val[0]].DamageTid;
              setTid({
                ...tid,
                damageTypeTid,
              });
              handleAtaChange('damageType', val, 'para', damageTypeTid);
            }}
          >
            <List.Item>损伤类型</List.Item>
          </Picker>
          <List.Item>位置描述</List.Item>
          <TextareaItem
            rows={4}
            editable={true}
            value={editDamage.damageDesc}
            onChange={(val) => handleChange('damageDesc', val)}
          />

          {ataParams.showArea &&
            ataParams.showArea.map((item, index) => {
              return (
                <InputItem
                  value={editDamage[item]}
                  onChange={(val) => handleChange(item, val)}
                >
                  {item}
                </InputItem>
              );
            })}
          <List.Item
            extra={
              <PhotoCameraPicker
                usePicker
                photos={damageRpt.closeShotPics}
                onFileChange={(file) =>
                  handlePicChange('closeShotPics', JSON.parse(file).FilePath)
                }
              />
            }
          >
            近景图片
          </List.Item>
          <List.Item
            extra={
              <PhotoCameraPicker
                usePicker
                photos={damageRpt.visionRangePics}
                onFileChange={(file) =>
                  handlePicChange('visionRangePics', JSON.parse(file).FilePath)
                }
              />
            }
          >
            远景图片
          </List.Item>
        </List>
      </ScrollView>
      <Flex>
        <Flex.Item>
          <Button
            type="primary"
            onPress={handleSubmit}
            loading={damageRptStore.submitDamageReport.loading}
          >
            提交
          </Button>
        </Flex.Item>
      </Flex>
    </>
  );
}

DamageReportSubmitPage.routeName = 'DamageReportSubmitPage';
DamageReportSubmitPage.permission = 'RDamageReportSubmit';
export default DamageReportSubmitPage;
